import axios from 'axios';
import moment from 'moment';
import Cookies from 'js-cookie';

const REQUEST_TIMEOUT = 300000;
const BASE_URL = '/api/WSYY';
const HEADERS = {
	'X-Requested-With': 'XMLHttpRequest',
	'x-csrf-token': Cookies.get('csrfToken') || undefined,
};

export const request = (
	{
		method = 'post',
		baseURL = BASE_URL,
		timeout = REQUEST_TIMEOUT,
		headers,
		url,
		data,
		success,
		fail,
	}) => {
	const defaultParams = {
		_: moment().valueOf(),
	};
	const params = data ? {
		...defaultParams,
		...data,
	} : defaultParams;
	axios({
		method,
		url,
		params: method === 'get' ? params : undefined,
		data: method !== 'get' ? params : undefined,
		timeout,
		baseURL,
		headers: {
			...HEADERS,
			...headers,
		},
	})
		.then(response => {
			success && success(response.data);
		})
		.catch(error => {
			if (error.response) {
				if (error.response.data) {
					fail && fail({
						msg: error.response.data.msg,
						status: error.response.status,
						data: error.response.data,
					});
				} else {
					fail && fail({
						msg: error.message,
						status: error.response.status,
					});
				}
			} else {
				fail && fail({ msg: error.message });
			}
		});
};
